import email.mime.text
import email.Header
import email.utils

import grok
from zope.component import getUtility
from zope.sendmail.interfaces import IMailDelivery

from LCAClassifier.web.interfaces import IMyMailer

defaultSender = ('CREST', 'services@cbu.uib.no')


class MyMail(grok.GlobalUtility):
    grok.implements(IMyMailer)

    def __init__(self, defaultSender=defaultSender):
        self.sender = defaultSender

    def send_mail(self, recipient, subject, body, sender=None):
        ''' format can be 'html' or 'plain' for example '''
        if sender is None:
            sender = self.sender
        mailer = getUtility(IMailDelivery, 'crestMailer')
        msg = email.mime.text.MIMEText(body.encode('UTF-8'), 'plain', 'UTF-8')
        msg["From"] = email.utils.formataddr(sender)
        msg["To"] = recipient
        msg["Subject"] = email.Header.Header(subject, 'UTF-8')
        mailer.send(sender[1], [recipient], msg.as_string())
